import { Sprite } from 'pixi.js';
import { Body } from 'matter-js';

export interface EntityConfig {
  id: string;
  x: number;
  y: number;
  width: number;
  height: number;
  sprite?: Sprite;
  body?: Body;
  tags?: string[];
}

export abstract class Entity {
  protected id: string;
  protected x: number;
  protected y: number;
  protected width: number;
  protected height: number;
  protected sprite?: Sprite;
  protected body?: Body;
  protected tags: Set<string>;
  protected isActive: boolean;

  constructor(config: EntityConfig) {
    this.id = config.id;
    this.x = config.x;
    this.y = config.y;
    this.width = config.width;
    this.height = config.height;
    this.sprite = config.sprite;
    this.body = config.body;
    this.tags = new Set(config.tags || []);
    this.isActive = true;
  }

  // 基础属性访问器
  public getId(): string { return this.id; }
  public getPosition(): { x: number; y: number } { return { x: this.x, y: this.y }; }
  public getSize(): { width: number; height: number } { return { width: this.width, height: this.height }; }
  public getSprite(): Sprite | undefined { return this.sprite; }
  public getBody(): Body | undefined { return this.body; }
  public getTags(): string[] { return Array.from(this.tags); }
  public isEntityActive(): boolean { return this.isActive; }

  // 实体状态管理
  public activate(): void { this.isActive = true; }
  public deactivate(): void { this.isActive = false; }
  public addTag(tag: string): void { this.tags.add(tag); }
  public removeTag(tag: string): void { this.tags.delete(tag); }
  public hasTag(tag: string): boolean { return this.tags.has(tag); }

  // 位置和运动更新
  public setPosition(x: number, y: number): void {
    this.x = x;
    this.y = y;
    if (this.sprite) {
      this.sprite.x = x;
      this.sprite.y = y;
    }
    if (this.body) {
      // @ts-ignore - Matter.js类型定义不完整
      Body.setPosition(this.body, { x, y });
    }
  }

  public setRotation(angle: number): void {
    if (this.sprite) {
      this.sprite.rotation = angle;
    }
    if (this.body) {
      // @ts-ignore - Matter.js类型定义不完整
      Body.setAngle(this.body, angle);
    }
  }

  // 碰撞检测
  public intersects(other: Entity): boolean {
    return this.x < other.x + other.width &&
           this.x + this.width > other.x &&
           this.y < other.y + other.height &&
           this.y + this.height > other.y;
  }

  // 生命周期方法
  public abstract update(delta: number): void;
  public abstract destroy(): void;
}